import { Request, Response } from 'express';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

async function getFakeCaptcha(req: Request, res: Response) {
  await waitTime(2000);
  return res.json('captcha-xxx');
}

const { ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION } = process.env;

/**
 * 当前用户的权限，如果为空代表没登录
 * current user access， if is '', user need login
 * 如果是 pro 的预览，默认是有权限的
 */
let access = ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site' ? 'admin' : '';

const getAccess = () => {
  return access;
};

// 代码中会兼容本地 service mock 以及部署站点的静态数据
export default {
  // 支持值为 Object 和 Array
  'GET /api-mock/currentUser': (req: Request, res: Response) => {
    // if (!getAccess()) {
    //   res.status(401).send({
    //     data: {
    //       isLogin: false,
    //     },
    //     errorCode: '401',
    //     errMessage: '请先登录！',
    //     code: -1,
    //   });
    //   return;
    // }
    res.send({
      code: 0,
      data: {
        username:"testadmin",
        role:"admin",
        name: 'Serati Ma',
        id: 1,
        email: 'antdesign@alipay.com',
        avatar: "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png"
      },
    });
  },
  // GET POST 可省略
  'GET /api-mock/users': {
    code:0,
    data:[
    {
      id: 1,
      username:"testadmin",
      role:"admin",
      nickname: 'Serati Ma',
      email: 'admin@test.com',
      created_at:"2021-10-01 11:11:11"
    },
    {
      id: 2,
      username:"testuser",
      role:"user",
      nickname: 'User Ma',
      email: 'user@test.com',
      created_at:"2021-10-02 13:20:11"
    },
  ]},
  'POST /api-mock/login/account': async (req: Request, res: Response) => {
    const { password, username, type } = req.body;
    if (password === 'ant.design' && username === 'admin') {
      res.send({
        code:0
      });
      access = 'admin';
      return;
    }
    res.send({
      code:-1,
      errMessage: 'error user',
    });
  },
  'POST /api-mock/login/outLogin': (req: Request, res: Response) => {
    access = '';
    res.send({ data: {}, success: true });
  },
  'POST /api/register': (req: Request, res: Response) => {
    res.send({ status: 'ok', currentAuthority: 'user', success: true });
  },

  'GET  /api/login/captcha': getFakeCaptcha,
};
